<!--
  * 「积分中心」页面，现用于2024年五一活动
  * @author: Ruan Jiazhen
  * @date: 2024-04-24  16:06:30
-->
<template>
  <div class="page" @click="closeAllBubble">
    <div class="body">
      <!-- 背景 -->
      <div class="bg">
        <image
          class="bg-img"
          src="https://ustatic.joymew.com/%20miao/top-bg.png"
        />
      </div>
      <!-- 导航栏 -->
      <uni-nav-bar
        class="nav-bar"
        background-color="#00000000"
        color="#fff"
        title="积分中心"
        :border="false"
        status-bar
      />
      <!-- 「查看榜单」按钮 -->
      <div class="check-rank-btn" @click="checkRankBtnClick">查看榜单</div>
      <div class="switch" :class="switchIndex === 0 ? 'on-left' : 'on-right'">
        <div class="left" @click="changeSwitchIndex(0)">巅峰赛</div>
        <div class="right" @click="changeSwitchIndex(1)">团队邀请赛</div>
        <div class="switch-bg">
          <div
            class="panel"
            :class="switchIndex === 0 ? 'on-left' : 'on-right'"
          />
        </div>
      </div>
      <!-- 个人巅峰赛信息 -->
      <div v-if="switchIndex === 0" class="my-info">
        <div class="title">我的积分</div>
        <div class="point">
          {{ personalPeakCompetitionInfo?.score || 0 }}
        </div>
        <div class="today-point">
          今日获得积分：<span class="red">{{
            personalPeakCompetitionInfo?.todayScore || 0
          }}</span>
        </div>
      </div>
      <!-- 团队邀请赛信息 -->
      <div v-if="switchIndex === 1" class="team-invite-compete-info">
        <div class="title">团队积分</div>
        <div class="point">
          {{ teamInviteCompetition?.score || 0 }}
        </div>
        <div class="today-point">
          今日获得积分：<span class="red">{{
            teamInviteCompetition?.todayScore || 0
          }}</span>
        </div>
        <!-- 成员积分 -->
        <div class="member-point">
          <div class="title">成员积分</div>
          <div
            v-if="!personInfo202310.isJoinTeam"
            class="member-item-area member-item-area--no-team"
          >
            暂未加入团队
          </div>
          <div class="member-item-area">
            <div
              v-for="member in teamInviteCompetition?.teamMemberList.slice(
                0,
                4
              )"
              :key="member.userId"
              class="member-item"
            >
              <image class="avatar" :src="member.avatar" mode="aspectFill" />
              <div class="point">
                {{ member.score || 0 }}
              </div>
            </div>
            <div
              class="member-item more-btn"
              v-if="teamInviteCompetition?.teamMemberList.length > 4"
              @click="showMoreMemberPoint"
            >
              <div class="more-round">
                <div class="dot" v-for="dot in 3" :key="dot"></div>
              </div>
              <div class="point">更多</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 任务 -->
      <div class="task">
        <!-- 每日任务 -->
        <div v-if="switchIndex === 1" class="task-list">
          <image class="task-list__bg" :src="COMMON_IMG_URL.TASK_LIST_BG" />
          <image class="coin-img" :src="IMG_URL.COIN" />
          <div class="task-list-name">
            <div class="decoration" />
            <text class="text"> 激励任务 </text>
            <text class="desc"> （系统自动发放） </text>
          </div>
          <!-- 任务列表内容 -->
          <div class="task-list-content">
            <TaskItem
              v-for="(taskItem, index) in DAILY_TASK_LIST"
              :ref="`taskItem${index}`"
              :key="index"
              :task-info="taskItem"
              :btn-disabled="taskItem.disabled || isBtnDisabled(taskItem.title)"
              :btn-text="getBtnText(taskItem)"
              @click-btn="btnClick(taskItem)"
            />
            <PointTaskItem
              v-for="(taskItem, index) in TEAM_TASK_LIST"
              :key="`taskItemPart2${index}`"
              :task-info="taskItem"
            />
          </div>
        </div>
        <!-- 互动任务 -->
        <div v-if="switchIndex === 0" class="task-list">
          <image class="task-list__bg" :src="COMMON_IMG_URL.TASK_LIST_BG" />
          <image class="coin-img" :src="IMG_URL.COIN" />
          <!-- 任务列表名称 -->
          <div class="task-list-name">
            <div class="decoration" />
            <text class="text"> 互动任务 </text>
            <text class="desc"> （系统自动发放） </text>
          </div>
          <!-- 任务列表内容 -->
          <div class="task-list-content">
            <PointTaskItem
              v-for="(taskItem, index) in POINTS_TASK_LIST"
              :key="index"
              :task-info="taskItem"
              :ref="`pointTaskItem${index}`"
              @clickBtn="pointTaskItemClickBtn(taskItem)"
            />
          </div>
          <!-- 任务列表底部提示 -->
          <div class="task-list-bottom-tip">
            <p class="text text--title">
              <span class="highlight">特别说明：活动使用互动</span>
            </p>
            <p class="text" style="margin-top: 8px">
              1场真实有效活动（签到人数大于30人）300积分
            </p>
          </div>
        </div>
        <!-- 激励任务 -->
        <div class="task-list" v-if="switchIndex === 0">
          <image class="task-list__bg" :src="COMMON_IMG_URL.TASK_LIST_BG" />
          <image class="coin-img" :src="IMG_URL.COIN" />
          <div class="task-list-name">
            <div class="decoration" />
            <text class="text"> 激励任务 </text>
            <text class="desc"> （系统自动发放） </text>
          </div>
          <!-- 任务列表内容 -->
          <div class="task-list-content">
            <TaskItem
              v-for="(taskItem, index) in REWAD_TASK_LIST"
              :ref="`rewardTaskItem${index}`"
              :key="index"
              :task-info="taskItem"
              :btn-disabled="taskItem.disabled || isBtnDisabled(taskItem.title)"
              :btn-text="getBtnText(taskItem)"
              @click-btn="btnClick(taskItem)"
            />
          </div>
        </div>
        <!-- 嗨喵App每日任务 -->
        <div class="task-list" v-if="switchIndex === 1">
          <image class="task-list__bg" :src="COMMON_IMG_URL.TASK_LIST_BG" />
          <image class="coin-img" :src="IMG_URL.COIN" />
          <div class="task-list-name">
            <div class="decoration" />
            <text class="text"> 嗨喵App每日任务 </text>
            <text class="desc"> （系统自动发放） </text>
          </div>
          <!-- 任务列表内容 -->
          <div class="task-list-content">
            <div class="task-list-content">
              <TaskItem
                v-for="(taskItem, index) in APP_TASK_LIST"
                :key="index"
                :task-info="taskItem"
                :btn-disabled="
                  taskItem.disabled || isBtnDisabled(taskItem.title)
                "
                :btn-text="getBtnText(taskItem)"
                @click-btn="btnClick(taskItem)"
                :ref="`AppTaskItem${index}`"
                :titleFontSize="27"
              />
            </div>
          </div>
        </div>
      </div>
      <ToLoginMask v-if="!isLogin" />
    </div>
  </div>
  <CustomTabBar />
  <CheckInSuccessPopup ref="checkInSuccessPopup" />
  <CreateTeamPopup ref="createTeamPopup" @confirm="onCreateTeamConfirm" />
  <MemberPoint
    ref="memberPointPopup"
    :teamMemberList="teamInviteCompetition?.teamMemberList"
  />
  <GetAppPopup ref="getAppPopup" />
  <!-- 客服二维码 -->
  <div class="qrcode-box" v-if="qrcodeVisible">
    <image
      src="https://ustatic.hudongmiao.com/miao/web/assist.7fad9761.png"
      :show-menu-by-longpress="true"
      class="qrcode-img"
    ></image>
    <image
      class="close-icon"
      src="https://ustatic.hudongmiao.com/%20miao/index/close-icon.png"
      @click="hideQrcode"
    ></image>
  </div>
</template>

<script lang="ts" setup>
import GetAppPopup from "@/components/activity-202410/GetAppPopup.vue";
import MemberPoint from "@/components/activity-202410/MemberPoint.vue";
import CheckInSuccessPopup from "@/components/CheckInSuccessPopup.vue";
import CreateTeamPopup from "@/components/CreateTeamPopup.vue";
import CustomTabBar from "@/components/CustomTabBar.vue";
import PointTaskItem from "@/components/PointTaskItem.vue";
import TaskItem from "@/components/TaskItem.vue";
import ToLoginMask from "@/components/ToLoginMask.vue";
import {
  APP_TASK_LIST,
  DAILY_TASK_LIST,
  IMG_URL,
  POINTS_TASK_LIST,
  REWAD_TASK_LIST,
  TEAM_TASK_LIST,
} from "@/static/constant/activity-202405-constant";
import { IMG_URL as COMMON_IMG_URL } from "@/static/constant/view-constant";
import { useActivity202310 } from "@/stores/activity-202310-store";
import { useUser } from "@/stores/user";
import {
  clickCheckIn,
  inviteFriend,
  onCreateTeamConfirm,
} from "@/utils/activity-202310-utils";
import { navigateTo } from "@/utils/navigate";

const userStore = useUser();
const { isLogin } = storeToRefs(userStore);

const activity202310Store = useActivity202310();
const {
  personalPeakCompetitionInfo,
  personInfo202310,
  teamInviteCompetition,
  appTasks,
} = storeToRefs(activity202310Store);

const { setPersonInfo202310, setTeamInviteCompetitionData } =
  activity202310Store;

const currentInstance = getCurrentInstance();

// #region 状态切换、查看榜单按钮
const switchIndex = ref(0);

const changeSwitchIndex = (index: 0 | 1) => {
  switchIndex.value = index;
};

const checkRankBtnClick = () => {
  switch (switchIndex.value) {
    case 0:
      navigateTo("personal-peak-competition");
      break;
    case 1:
      uni.switchTab({ url: "/pages/team-invitation-competition" });
      break;
    default:
      break;
  }
};

// #endregion

// #region 信息获取和展示相关

/** 检查并获取相关信息 */
const checkAndGetInfo = () => {
  if (!personalPeakCompetitionInfo.value) {
    setPersonInfo202310();
  }
  if (!teamInviteCompetition.value) {
    setTeamInviteCompetitionData();
  }
};

onShow(() => {
  checkAndGetInfo();

  console.log(personInfo202310.value);
});

// #endregion

// #region 按钮相关

/** 按钮是否可用
 * @param taskTitle 任务标题
 */
const isBtnDisabled = (
  taskTitle: (typeof DAILY_TASK_LIST)[number]["title"]
) => {
  switch (taskTitle) {
    case "组建团队":
      return personInfo202310.value.isJoinTeam;
    case "每日签到":
      return teamInviteCompetition.value?.isCheckIn;
    case "真实团队认证":
      return teamInviteCompetition.value?.auth_status === "1";
    case "每天登录嗨喵APP": {
      return checkAppTaskFinish(taskTitle);
    }
    case "发布一条个人作品": {
      return checkAppTaskFinish(taskTitle);
    }
    case "发布一条圈子动态": {
      return checkAppTaskFinish(taskTitle);
    }
    case "创建一个个人档期": {
      return checkAppTaskFinish(taskTitle);
    }
    default:
      return false;
  }
};

/** 按钮文本
 * @param taskItem 任务项
 */
const getBtnText = (taskItem: (typeof DAILY_TASK_LIST)[number]) => {
  switch (taskItem.title) {
    case "组建团队":
      return (teamInviteCompetition.value?.teamMemberList?.length ?? 0) >= 3
        ? "已完成"
        : taskItem.btnText;
    case "每日签到":
      return teamInviteCompetition.value?.isCheckIn
        ? "已签到"
        : taskItem.btnText;
    case "完成一场有效活动":
      return "去完成";
    default:
      return taskItem.btnText;
  }
};

const qrcodeVisible = ref(false);

const hideQrcode = () => {
  qrcodeVisible.value = false;
};

/**
 * 按钮点击事件
 * @param taskItem 任务项
 */
const btnClick = (taskItem: (typeof DAILY_TASK_LIST)[number]) => {
  console.log(taskItem);
  switch (taskItem.title) {
    case "组建团队":
      if (!personInfo202310.value.isJoinTeam) {
        const createTeamPopup = currentInstance?.refs
          .createTeamPopup as typeof CreateTeamPopup;
        createTeamPopup?.open();
      }
      break;
    case "每日签到":
      clickCheckIn(currentInstance);
      break;
    case "邀请新用户注册使用":
      // 跳转嗨喵助手注册页面
      uni.navigateToMiniProgram({
        appId: "wxedf32538e9a5f880",
        path: "pages/inviteTest/inviteTest",
        envVersion: "release",
      });
      break;
    case "分销婚礼娃娃":
      // 跳转嗨喵助手婚品商城页面
      // 跳转嗨喵助手注册页面
      uni.navigateToMiniProgram({
        appId: "wxedf32538e9a5f880",
        path: "pages/activity/shop/shop",
        envVersion: "release",
      });
      break;
    case "真实团队认证": {
      if (!taskItem.disabled) {
        qrcodeVisible.value = true;
      }
      break;
    }
    case "每天登录嗨喵APP":
    case "发布一条个人作品":
    case "发布一条圈子动态":
    case "创建一个个人档期": {
      showGetAppPopup(taskItem.title);
      break;
    }
    default:
      break;
  }
};

/**
 * 显示更多成员积分
 */
const showMoreMemberPoint = () => {
  const memberPointPopup = currentInstance?.refs
    .memberPointPopup as typeof MemberPoint;
  memberPointPopup?.open();
};

const appTaskMap = {
  每天登录嗨喵APP: "loginHaimiao",
  发布一条个人作品: "publishWorks",
  发布一条圈子动态: "publishCircle",
  创建一个个人档期: "createSchedule",
};

/**
 * 检查当前嗨喵App任务是否完成
 */
const checkAppTaskFinish = (taskTitle: string) => {
  const taskType = appTaskMap[taskTitle];
  const task = appTasks.value?.find((item) => item.type === taskType);
  return task?.score !== "0";
};

/**
 * 打开进入嗨喵App的提示弹窗
 */
const showGetAppPopup = (taskTitle) => {
  // 任务已完成则不弹窗
  if (checkAppTaskFinish(taskTitle)) {
    return;
  }
  const getAppPopup = currentInstance?.refs.getAppPopup as typeof GetAppPopup;
  getAppPopup?.open();
};

// #endregion

/** 关闭所有气泡 */
const closeAllBubble = () => {
  if (currentInstance?.refs[`taskItem${0}`]) {
    for (let i = 0; i < DAILY_TASK_LIST.length; i += 1) {
      const taskItem = (
        currentInstance?.refs[`taskItem${i}`] as InstanceType<typeof TaskItem>[]
      )[0];
      taskItem.closeBubble();
    }
  }
  if (currentInstance?.refs[`pointTaskItem${0}`]) {
    for (let i = 0; i < POINTS_TASK_LIST.length; i += 1) {
      const pointTaskItem = (
        currentInstance?.refs[`pointTaskItem${i}`] as InstanceType<
          typeof PointTaskItem
        >[]
      )[0];
      pointTaskItem.closeBubble();
    }
  }
};

// 积分任务点击事件处理
const pointTaskItemClickBtn = (taskItem: (typeof POINTS_TASK_LIST)[number]) => {
  console.log(taskItem);
  // 点击了创建活动
  if (taskItem.title === "完成一场有效活动") {
    // 跳转另一个小程序嗨喵助手的申请活动页面
    uni.navigateToMiniProgram({
      appId: "wxedf32538e9a5f880",
      path: "pages/index/applyActivity/applyActivity",
      envVersion: "release",
    });
  }
};

onShareAppMessage(() => inviteFriend());
</script>

<style lang="scss" scoped>
$text-color: #333;

.page {
  position: relative;

  width: 100vw;
  height: 100vh;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  .body {
    position: relative;
    z-index: 10;

    width: 100vw;
    min-height: 100%;

    background-color: #edf8ea;

    padding-bottom: calc($tabBarHeight + env(safe-area-inset-bottom));
    display: grid;
    grid-template:
      "nav-bar" min-content
      "." 10px
      "switch" min-content
      "." 16px
      "my-info" min-content
      "." 16px
      "task" min-content
      "." 44px
      / 1fr;
    place-items: center;

    // 背景
    .bg {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -2;

      width: 100vw;
      min-height: 100%;

      .bg-img {
        width: 100vw;
        height: 73.6vw;
      }
    }

    // 导航栏
    .nav-bar {
      grid-area: nav-bar;
    }

    .check-rank-btn {
      position: absolute;
      top: 109px;
      right: 0;

      width: 60px;
      height: 22px;

      background: rgba($color: #000, $alpha: 60%);
      border-radius: 11px 0 0 11px;

      display: flex;
      align-items: center;
      justify-content: center;

      font-size: 10px;
      color: #fff;
    }

    .switch {
      grid-area: switch;

      position: relative;

      width: 170px;
      height: 36px;

      display: grid;
      grid-template-columns: 1fr 1fr;
      place-items: center;

      font-size: 13px;
      color: #ff403c;

      &.on-left {
        .left {
          color: #fff;
        }
      }

      &.on-right {
        .right {
          color: #fff;
        }
      }

      .switch-bg {
        position: absolute;
        z-index: -1;

        width: 100%;
        height: 100%;

        background: #fff;
        border-radius: 51px;

        .panel {
          position: absolute;
          top: 50%;

          width: 80px;
          height: 28px;

          background: #ff403c;
          border-radius: 51px;

          transform: translateY(-50%);

          &.on-left {
            left: 4px;
          }

          &.on-right {
            right: 4px;
          }
        }
      }
    }

    .my-info {
      grid-area: my-info;

      height: 94px;

      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;

      color: #fff;

      .title {
        font-size: 17px;
      }

      .point {
        font-size: 36px;
        font-weight: bold;
      }

      .today-point {
        font-size: 15px;

        .red {
          color: #ff2459;
        }
      }
    }

    .team-invite-compete-info {
      grid-area: my-info;

      width: 100%;
      height: 94px;

      padding: 0 20px 0 28px;
      display: grid;
      grid-template:
        "title member-point" min-content
        "point member-point" min-content
        "today-point member-point" min-content
        / max-content 1fr;
      justify-items: start;

      color: #fff;

      .title {
        grid-area: title;

        font-size: 17px;
      }

      .point {
        grid-area: point;

        font-size: 36px;
        font-weight: bold;
      }

      .today-point {
        grid-area: today-point;

        font-size: 15px;

        .red {
          color: #ff2459;
        }
      }

      .member-point {
        grid-area: member-point;

        width: 100%;

        display: grid;
        grid-template:
          "title" min-content
          "member-item-area" min-content
          / 1fr;
        row-gap: 10px;
        column-gap: 8px;
        justify-items: center;

        .title {
          grid-area: title;

          font-size: 17px;
        }

        .member-item-area {
          grid-area: member-item-area;

          width: 100%;

          display: flex;
          gap: 13px;
          align-items: center;
          justify-content: center;

          .member-item {
            display: flex;
            flex-direction: column;
            row-gap: 4px;
            align-items: center;
            justify-content: center;

            .avatar {
              width: 28px;
              height: 28px;

              border: 1px solid #fff;
              border-radius: 50%;
            }

            .point {
              font-size: 11px;
              color: #fff;
            }
            .more-round {
              width: 46rpx;
              height: 46rpx;
              border-radius: 50%;
              background-color: rgba($color: #fff, $alpha: 40%);
              display: flex;
              justify-content: space-evenly;
              align-items: center;
              .dot {
                width: 8rpx;
                height: 8rpx;
                background-color: #fff;
                border-radius: 50%;
              }
            }
          }
        }
      }
    }

    // 任务
    .task {
      grid-area: task;
      justify-self: center;

      display: flex;
      flex-direction: column;
      row-gap: 66px;
      align-items: center;

      // 任务列表
      .task-list {
        position: relative;

        width: calc(100vw - 32px);

        padding: 15px 16px 23px;
        display: flex;
        flex-direction: column;
        align-items: center;

        &__bg {
          position: absolute;
          top: 0;
          left: 0;
          z-index: -1;

          width: 100%;
          height: 100%;
        }

        .coin-img {
          position: absolute;
          top: -8px;
          right: 10px;
          z-index: -2;

          width: 64px;
          height: 66px;
        }

        .task-list-name {
          width: 100%;
          height: 28px;

          display: flex;
          column-gap: 8px;
          align-items: center;

          // 名称前的装饰
          .decoration {
            width: 9px;
            height: 9px;

            border: 1.5px solid #ff2459;
            border-radius: 50%;
          }

          // 名称
          .text {
            font-size: 20px;
            font-weight: 600;
            color: #333;
          }

          // 注释
          .desc {
            font-size: 15px;
            color: #8d8d8d;
          }
        }

        // 任务列表内容
        .task-list-content {
          width: 100%;

          padding: 16px 0;
          display: grid;
          grid-template-rows: repeat(auto-fill, minmax(40px, min-content));
          row-gap: 28px;
        }

        .task-list-bottom-tip {
          display: flex;
          flex-direction: column;
          justify-content: center;

          font-size: 13px;

          .text {
            &--title {
              align-self: center;
            }

            .highlight {
              color: #ff2459;
            }
          }
        }
      }
    }
  }
}
.qrcode-box {
  position: fixed;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .qrcode-img {
    width: 520rpx;
    height: 520rpx;
  }
  .close-icon {
    margin-top: 20rpx;
    width: 92rpx;
    height: 92rpx;
  }
}
</style>
